package thread;

public class Test9_deamon {
    public static void main(String[] args) {
        Thread t1 = new CommonThread();
        //新建任务，再绑定到一个线程上
        Thread t2 = new Thread(new MyDeamon());
        //设置为守护线程
        t2.setDaemon(true);
        //正确做法：线程运行前设置守护线程
        t2.start();
        t1.start();
        System.out.println("主线程结束");
    }
}

//线程类
class CommonThread extends Thread{
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            System.out.println("用户线程第"+i+"次执行！");
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

//任务类
class MyDeamon implements Runnable{
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            System.out.println("守护线程第"+i+"次执行！");
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}